//
//  STOrderHistoryContentViewController.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/11/28.
//

import UIKit
import MJRefresh

class STOrderHistoryContentViewController: GPBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout  {
    
    public var type: Int!
    let pageSize = 20
    var pageNum: Int = 1
    var total: Int = 0
    var dataSource: Array<Dictionary<String, Any>> = []
    let requestApi = GPRequestApi.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.init(hexString: "#FFFFFF", alpha: 0)

        addSubviewForPage()
        showLoading("正在加载...")
        requestOrderList()
    }
    
    func addSubviewForPage() {
        view.addSubview(listView)
        STOrderHistoryCollectionViewCell.registerTo(listView)
        
        view.addSubview(nonDataView)
        nonDataView.snp.makeConstraints { (make) in
            make.top.equalTo(0)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(454)
        }
        
        // 下拉刷新
        mj_header.setRefreshingTarget(self, refreshingAction: #selector(STOrderHistoryContentViewController.headerRefresh))
        // 上拉刷新
        mj_footer.setRefreshingTarget(self, refreshingAction: #selector(STOrderHistoryContentViewController.footerRefresh))
        listView.mj_header = mj_header
        listView.mj_footer = mj_footer
        nonDataView.isHidden = true
    }
    
    func requestOrderList() {
        requestApi.getHistoryOrderList(["orderType": type ?? 0, "pageNum": pageNum, "pageSize": pageSize]) { (isSuccess, response, error)  in
            self.mj_header.endRefreshing()
            self.hideLoading()
            if(isSuccess) {
                let responseData = response as! Dictionary<String, Any>
                let rows = responseData["rows"] as! Array<Dictionary<String, Any>>
                let total = responseData["total"] as! Int
                if(rows.count > 0) {
                    self.updatDataSource(dataSource: rows, forTotalRows: total)
                }
                if(total == 0) {
                    self.nonDataView.isHidden = false
                    self.listView.isHidden = true
                } else {
                    self.total = total
                    if(self.pageNum == 1) {
                        self.dataSource = rows
                    } else {
                        self.dataSource.append(contentsOf: rows)
                    }
                    self.listView.reloadData()
                    if (self.pageNum * self.pageSize < self.total) {
                        self.mj_footer.endRefreshing()
                    } else {
                        self.mj_footer.endRefreshingWithNoMoreData()
                    }
                }
            } else {
                self.mj_footer.endRefreshing()
                self.toastError(error!.1)
            }
        }
    }
    
    public func updatDataSource (dataSource data: Array<Dictionary<String, Any>>, forTotalRows totalNum: Int ) {
        total = totalNum
        dataSource = data
        listView.reloadData()
    }
    
    // UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let h = 224 * (kScreenWidth - 32) / 343
        return CGSize.init(width: kScreenWidth - 32, height: h)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = STOrderHistoryCollectionViewCell.reusableCell(collectionView, indexPath: indexPath)
        let item = dataSource[indexPath.item]
        cell?.updateData(data: item, type: type,  indexPath.item)
        return cell ?? collectionView.dequeueReusableCell(withReuseIdentifier: STOrderHistoryCollectionViewCell.identifier, for: indexPath)
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        pageNum = 1
        requestOrderList()
    }

    // 底部刷新
    @objc func footerRefresh(){
        if (pageNum * pageSize < total) {
            pageNum = pageNum + 1
            requestOrderList()
        } else {
            mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    // 懒加载
    lazy var listView: UICollectionView = {
        let size = self.view.bounds.size
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 0
        let collectView: UICollectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: size.width, height: size.height - 88), collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = UIColor.white
        collectView.layer.cornerRadius = 8
        collectView.backgroundColor = UIColor.init(hexString: "#F7F7F7", alpha: 1)
        return collectView
    }()

    lazy var mj_header: MJRefreshNormalHeader = {
        let header = MJRefreshNormalHeader()
        header.setTitle("下拉刷新", for: .idle)
        header.setTitle("释放更新", for: .pulling)
        header.setTitle("正在刷新...", for: .refreshing)
        return header
    }()
    
    lazy var mj_footer: MJRefreshAutoNormalFooter = {
        let footer = MJRefreshAutoNormalFooter()
        footer.isAutomaticallyRefresh = false
        footer.isAutomaticallyChangeAlpha = true
        footer.setTitle("上拉刷新", for: .idle)
        footer.setTitle("正在加载...", for: .refreshing)
        footer.setTitle("已加载全部数据", for: .noMoreData)
        return footer
    }()
    
    lazy var nonDataView: STOrderNonDataView = {
        let v = STOrderNonDataView.init(frame: CGRect.zero)
        return v
    }()
    
}

class STOrderNonDataView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 12
        backgroundColor = UIColor.white
        
        let imgView: UIImageView = UIImageView.init(image: UIImage.init(named: "img_nondata"))
        addSubview(imgView)
        imgView.snp.makeConstraints { (make) in
            make.top.equalTo(42)
            make.centerX.equalTo(self)
            make.width.equalTo(74)
            make.height.equalTo(74)
        }
        
        let lb = UILabel.init()
        lb.text = "暂无订单"
        lb.textAlignment = .center
        lb.textColor = UIColor.init(hexString: "#8F92A1", alpha: 1)
        lb.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.heavy)
        addSubview(lb)
        lb.snp.makeConstraints { (make) in
            make.top.equalTo(imgView.snp.bottom).offset(2)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(22)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
